package com.lp.sys.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.iframework.commons.domain.enums.HttpStatusCode;
import org.iframework.commons.domain.enums.RecordStatus;
import org.iframework.commons.domain.order.Order;
import org.iframework.commons.domain.pager.Pager;
import org.iframework.commons.util.MD5Util;
import org.iframework.commons.util.fast.L;
import org.iframework.commons.util.fast.V;
import org.iframework.support.spring.cache.api.BaseCacheManager;
import org.iframework.support.spring.hibernate.service.BaseServiceSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.lp.business.domain.JsonResultModel;
import com.lp.business.model.Access;
import com.lp.business.model.User;
import com.lp.business.service.AccessService;
import com.lp.sys.controller.base.BaseController;



@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController<User, String> {
	@Autowired
	private AccessService accessService;
	@Resource(name = "baseCacheManager")
	private BaseCacheManager cacheManager;
	
	@Resource(name = "userService")
	@Override
	public void setBaseServiceSupport(BaseServiceSupport<User, String> baseService) {
		super.setBaseServiceSupport(baseService);
	}
	/**
	 * 加载分页列表数据
	 */
	@RequestMapping(value = "list", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView list(HttpServletRequest request,HttpServletResponse response, User model) {
		
		ModelAndView modelAndView = new ModelAndView("/user/pageList");
		model.setStatus(RecordStatus.AVAILABLE);
		Pager pager = this.getPager(request);
		Order order = this.getOrder(request);
		List<User> models = this.baseService.findByModel(model, order, pager);
		modelAndView.addObject("models", models);
		modelAndView.addObject("page", pager);

		return modelAndView;
	}


	/**
	 * 进行保存操作
	 */
	@RequestMapping(value = "save", method = {RequestMethod.POST, RequestMethod.GET})
	public void save(HttpServletRequest request, HttpServletResponse response, User model) {
		
		try {
			if (V.isEmpty(model.getLoginPwd())||V.isEmpty(model.getReloginPwd())||!model.getLoginPwd().equals(model.getReloginPwd())){
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "密码和重复密码不一致").toSysJsonString(), response);
				return;
			}
			model.setLoginPwd(MD5Util.MD5Encode(model.getLoginPwd(),1));
			if (V.isNotEmpty(this.baseService.save(model))) {
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "新建保存操作成功").toSysJsonString(), response);
				return;
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "新建保存操作失败").toSysJsonString(), response);
				return;
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试").toSysJsonString(), response);
			return;
		}
	}
	
	/**
	 * 进行更新操作
	 */
	@RequestMapping(value = "update", method = {RequestMethod.POST, RequestMethod.GET})
	public void update(HttpServletRequest request, HttpServletResponse response, User model) {
		try {
			//校验是否传入id信息
			if (V.isEmpty(model.getId())) {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "ID必须填写").toSysJsonString(), response);
				return;
			}
			//校验是否存在相应数据
			User oldUser =  this.baseService.get(model.getId());
			if (V.isEmpty(oldUser)) {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "找不到需要更新的数据").toSysJsonString(), response);
				return;
			}
			String passwordUpdatable = request.getParameter("passwordUpdatable");
			if ("0".equals(passwordUpdatable)) {
				//不编辑密码
			} else if ("1".equals(passwordUpdatable)) {
//				//编辑密码
//				String oldValidLoginName = oldUser.getLoginPwd();//存于数据库中的原密码
//				String oldLoginPwd = request.getParameter("oldLoginPwd");//原密码
//				if (V.isEmpty(oldLoginPwd) || !oldValidLoginName.equals(MD5Util.MD5Encode(oldLoginPwd,1))) {
//					renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "原密码输入错误").toSysJsonString(), response);
//					return;
//				}
				String updateLoginPwd = request.getParameter("updateLoginPwd");//新密码
				String updateReloginPwd = request.getParameter("updateReloginPwd");//重复新密码
				if (V.isEmpty(updateLoginPwd) || V.isEmpty(updateReloginPwd) || !updateLoginPwd.equals(updateReloginPwd)){
					renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "新密码和重复密码不一致").toSysJsonString(), response);
					return;
				}
				model.setLoginPwd(MD5Util.MD5Encode(updateLoginPwd,1));
			}
			
			if (this.baseService.update(model)) {
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "更新修改操作成功").toSysJsonString(), response);
				return;
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "更新修改操作失败").toSysJsonString(), response);
				return;
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试").toSysJsonString(), response);
			return;
		}
	}
	

	@RequestMapping(value = "userInfo", method = {RequestMethod.POST, RequestMethod.GET})
	public ModelAndView userInfo(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView modelAndView = new ModelAndView("/user/userInfo");
//		String mobile = (String)request.getAttribute("mobile");
//		User u = (User)cacheManager.loadObject(mobile + "_settlement_adminSessionInfo"); 
		User u = (User) request.getSession().getAttribute("adminSessionInfo");	
		if (V.isEmpty(u)) {
			L.i("未登入！");
			return null;
		}
		String uid = u.getId();
		User model = this.baseService.get(uid); //根据id获取模型数据
		modelAndView.addObject("model", model);
		return modelAndView;
	}

	
	@RequestMapping(value = "modifyPassword", method = {RequestMethod.POST, RequestMethod.GET})
	public ModelAndView modifyPassword(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView modelAndView = new ModelAndView("/user/modifyPassword");
//		String mobile = (String)request.getAttribute("mobile");
//		User u = (User)cacheManager.loadObject(mobile + "_settlement_adminSessionInfo"); 
		User u = (User) request.getSession().getAttribute("adminSessionInfo");
		if (V.isEmpty(u)) {
			L.i("未登入！");
			return null;
		}
		String uid = u.getId();
		User model = this.baseService.get(uid); //根据id获取模型数据
		modelAndView.addObject("model", model);
		return modelAndView;
	}

	/**
	 * 进行更新密码操作
	 */
	@RequestMapping(value = "updatePassword", method = {RequestMethod.POST, RequestMethod.GET})
	public void updatePassword(HttpServletRequest request, HttpServletResponse response, String uid) {
		try {
//			String mobile = (String)request.getAttribute("mobile");
//			User LinUser = (User)cacheManager.loadObject(mobile + "_settlement_adminSessionInfo"); 
			User loginUser = (User) request.getSession().getAttribute("adminSessionInfo");
			if (V.isEmpty(loginUser)) {
				L.i("未登入！");
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "请先登录").toSysJsonString(), response);
				return;
			}
			User oldUser = this.baseService.get(uid);
			if (V.isEmpty(oldUser)) {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "当前编辑账号有误").toSysJsonString(), response);
				return;
			}
			//编辑密码
			String oldValidLoginName = oldUser.getLoginPwd();//存于数据库中的原密码
			
			String oldLoginPwd = request.getParameter("oldLoginPwd");//原密码
			String updateLoginPwd = request.getParameter("updateLoginPwd");//新密码
			String updateReLoginPwd = request.getParameter("updateReLoginPwd");//重复新密码
			if (V.isEmpty(oldLoginPwd) || !oldValidLoginName.equals(MD5Util.MD5Encode(oldLoginPwd,1))) {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "原密码输入错误").toSysJsonString(), response);
				return;
			}
			if (V.isEmpty(updateLoginPwd) || V.isEmpty(updateReLoginPwd) || !updateLoginPwd.equals(updateReLoginPwd)){
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "新密码和重复密码不一致").toSysJsonString(), response);
				return;
			}
			User model = new User();
			model.setId(uid);
			model.setLoginPwd(MD5Util.MD5Encode(updateLoginPwd,1));
			
			if (this.baseService.update(model)) {
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "更新密码操作成功").toSysJsonString(), response);
				return;
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "更新密码操作失败").toSysJsonString(), response);
				return;
			}
			
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试").toSysJsonString(), response);
			return;
		}
	}
	
	/**
	 * 进行批量删除操作
	 */
	@RequestMapping(value = "batchDelete", method = { RequestMethod.POST, RequestMethod.GET })
	public void batchDelete(HttpServletRequest request, HttpServletResponse response) {
		//1.执行必填校验
		String[] ids = request.getParameterValues("ids[]");
		if (V.isEmpty(ids)) {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "请选择需要删除的信息").toSysJsonString(), response);
			return;
		}
		//2.执行删除
		try {
			Collection<User> models = new ArrayList<User>();
			for (String id : ids) {
				//校验是否有此id的数据
				User model = this.baseService.get(id);
				if(V.isEmpty(model)){
					renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "删除失败，未找到需要删除的数据").toSysJsonString(), response);
					return;
				}
				models.add(model);
			}
			if(this.baseService.deleteAllVirtual(models)){
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "批量删除操作成功").toSysJsonString(), response);
				return;
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "批量删除操作失败").toSysJsonString(), response);
				return;
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试。").toSysJsonString(), response);
			return;
		}
	}

	/**
	 * 添加用户权限（ajax）
	 */
	@RequestMapping(value = "addUserAccess", method = {
			RequestMethod.POST, RequestMethod.GET
	})
	public void addUserAccess(HttpServletRequest request, HttpServletResponse response) {
		String[] items = request.getParameter("items").split(",");
		String userId = request.getParameter("userId");
		Collection<Access> models = new ArrayList<Access>();
		for (String item : items) {
			if (item.indexOf("_") > 0) {
				String[] itemStr = item.split("_");
				Access access1 = new Access();// 方法
				access1.setUserId(userId);
				access1.setMenuId(itemStr[0]);
				access1.setMenuMethodId(itemStr[1]);
				access1.setStatus(RecordStatus.AVAILABLE);
				access1.setCreateTime(new Date());
				access1.setUpdateTime(new Date());
				models.add(access1);
				Access access = new Access();// 菜单
				access.setUserId(userId);
				access.setMenuId(itemStr[0]);
				access.setStatus(RecordStatus.AVAILABLE);
				access.setCreateTime(new Date());
				access.setUpdateTime(new Date());
				models.add(access);
			} else {
				Access access = new Access();
				access.setUserId(userId);
				access.setMenuId(item);
				access.setStatus(RecordStatus.AVAILABLE);
				access.setCreateTime(new Date());
				access.setUpdateTime(new Date());
				models.add(access);
			}
		}
		this.accessService.addUserAccessList(models);
	}

	/**
	 * 移除角色组权限（ajax）
	 */
	@RequestMapping(value = "removeUserAccess", method = {
			RequestMethod.POST, RequestMethod.GET
	})
	public void removeUserAccess(HttpServletRequest request, HttpServletResponse response) {
		String[] items = request.getParameter("items").split(",");
		String userId = request.getParameter("userId");
		Collection<Access> models = new ArrayList<Access>();
		for (String item : items) {
			Access access = new Access();
			access.setUserId(userId);
			if (item.indexOf("_") > 0) {
				String[] itemStr = item.split("_");
				access.setMenuId(itemStr[0]);
				access.setMenuMethodId(itemStr[1]);
			} else {
				access.setMenuId(item);
			}
			access.setStatus(RecordStatus.AVAILABLE);
			List<Access> accesses = this.accessService.findByModel(access, null, null);
			if (accesses != null && accesses.size() > 0) {
				models.add(accesses.get(0));
			}
		}
		this.accessService.deleteUserAccessList(models);
	}

}
